package com.ruoyi.business.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;


import java.util.Date;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.business.dao.TestTreeDao;
import com.ruoyi.business.domain.TestTree;
import com.ruoyi.business.service.ITestTreeService;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 * test_treeService业务层处理
 *
 * @author liutietou
 * @since 1.0 2025-01-09
 */
@Transactional(readOnly = true)
@Service
public class TestTreeServiceImpl implements ITestTreeService {

    @Autowired
    private TestTreeDao testTreeDao;

    /**
     * 查询test_tree
     *
     * @param id test_treeID
     * @return test_tree
     */
    @Override
    public TestTree findById(Long id) {
        return testTreeDao.findById(id).get();
    }

    /**
     * 分页查询test_tree列表
     *
     * @param req test_tree
     * @return test_tree
     */
    @Override
    public Page<TestTree> findTestTreePage(TestTree req) {
        Specification<TestTree> example = formatQueryParams(req);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Pageable pageable = PageRequest.of(pageDomain.getPageNo(),
                Optional.ofNullable(pageDomain.getPageSize()).orElse(PageDomain.DEFAULT_PAGE_SIZE),
                Sort.Direction.DESC,
                Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("id"));
        Page<TestTree> page = testTreeDao.findAll(example, pageable);
        return page;
    }


//    @Override
//    public List<TestTree> findTestTreeList(TestTree req) {
//        // 构造 Specification，动态生成查询条件
//        Specification<TestTree> example = formatQueryParams(req);
//
//        // 获取排序字段和方向
//        PageDomain pageDomain = TableSupport.buildPageRequest();
//        String orderByColumn = Optional.ofNullable(pageDomain.getOrderByColumn()).orElse("id");
////        Sort.Direction sortDirection = Optional.ofNullable(pageDomain.getSortDirection()).orElse(Sort.Direction.DESC);
//
//        // 创建排序对象
//        Sort sort = Sort.by(sortDirection, orderByColumn);
//
//        // 查询所有符合条件的记录，返回 List
//        return testTreeDao.findAll(example, sort);
//    }

    /**
     * 分页查询test_tree列表
     *
     * @param req test_tree
     * @return test_tree
     */
    @Override
    public List<TestTree> findTestTreeList(TestTree req) {
        Specification<TestTree> example = formatQueryParams(req);
        List<TestTree> list = testTreeDao.findAll(example, Sort.by(Sort.Direction.DESC,"id"));
        return list;
    }

    private Specification<TestTree> formatQueryParams(TestTree req){
        Specification<TestTree> example = new Specification<TestTree>() {
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<TestTree> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<>();
                if (null != req.getId()){
                    Predicate pre = cb.equal(root.get("id").as(Long.class), req.getId());
                    list.add(pre);
                }
                if (null != req.getPid()){
                    Predicate pre = cb.equal(root.get("pid").as(Long.class), req.getPid());
                    list.add(pre);
                }
                if (StringUtils.isNotBlank(req.getName())){
                    Predicate pre = cb.like(root.get("name").as(String.class), "%" + req.getName()+ "%");
                    list.add(pre);
                }
                if (list.isEmpty()) {
                    return null;
                }
                return cb.and(list.toArray(new Predicate[0]));
            }
        };
        return example;
    }

    /**
     * 保存（新增/修改）test_tree
     *
     * @param testTree test_tree
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void save(TestTree testTree) {
        testTreeDao.save(testTree);
    }


    /**
     * 批量删除test_tree
     *
     * @param ids 需要删除的test_treeID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteByIds(List<Long> ids) {
        List<TestTree> existBeans = testTreeDao.findAllById(ids);
        if(!existBeans.isEmpty()){
            testTreeDao.deleteAll(existBeans);
        }
    }

    /**
     * 删除test_tree信息
     *
     * @param id test_treeID
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteTestTreeById(Long id) {
         testTreeDao.deleteById(id);
    }
}
